package com.dd.logistics.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.logistics.common.Result;
import com.dd.logistics.entity.Inventory;
import com.dd.logistics.entity.InventoryHistory;
import com.dd.logistics.entity.SupplierProduct;
import com.dd.logistics.service.InventoryService;
import com.dd.logistics.service.SupplierProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/inventory")
@Slf4j
public class InventoryController {
    
    @Autowired
    private InventoryService inventoryService;
    
    @Autowired
    private SupplierProductService supplierProductService;
    
    @GetMapping("/page")
    public Result<Page<Inventory>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String productCode,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) String location) {
        try {
            if (current < 1) {
                return Result.error("页码必须大于0");
            }
            if (size < 1 || size > 100) {
                return Result.error("每页条数必须在1-100之间");
            }
            
            Page<Inventory> page = inventoryService.getPage(current, size, productCode, productName, location);
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询库存失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/detail/{id}")
    public Result<Map<String, Object>> getDetail(@PathVariable Long id) {
        try {
            if (id == null) {
                return Result.error("库存ID不能为空");
            }
            
            Inventory inventory = inventoryService.getById(id);
            if (inventory == null) {
                return Result.error("库存记录不存在");
            }
            
            SupplierProduct product = supplierProductService.getById(inventory.getProductId());
            
            Map<String, Object> result = new HashMap<>();
            result.put("inventory", inventory);
            result.put("product", product);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询库存详情失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/list")
    public Result<List<Inventory>> list() {
        try {
            log.info("查询所有库存");
            List<Inventory> list = inventoryService.list();
            return Result.success(list);
        } catch (Exception e) {
            log.error("查询所有库存失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/update")
    public Result<Boolean> updateQuantity(
            @RequestParam String productCode,
            @RequestParam Integer adjustQuantity) {
        try {
            if (productCode == null || productCode.trim().isEmpty()) {
                return Result.error("商品编码不能为空");
            }
            if (adjustQuantity == null) {
                return Result.error("调整数量不能为空");
            }
            
            boolean success = inventoryService.updateQuantity(productCode, adjustQuantity);
            String type = adjustQuantity > 0 ? "入库" : "出库";
            return success ? Result.success(type + "成功", true) : Result.error(type + "失败");
        } catch (Exception e) {
            log.error("更新库存失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/update-info")
    public Result<Boolean> updateInfo(@RequestBody Inventory inventory) {
        try {
            if (inventory.getId() == null) {
                return Result.error("库存ID不能为空");
            }
            if (inventory.getLocation() == null || inventory.getLocation().trim().isEmpty()) {
                return Result.error("库位不能为空");
            }
            if (inventory.getWarningThreshold() == null || inventory.getWarningThreshold() < 0) {
                return Result.error("预警阈值不能为空且必须大于等于0");
            }
            
            boolean success = inventoryService.updateById(inventory);
            return success ? Result.success("更新信息成功", true) : Result.error("更新信息失败");
        } catch (Exception e) {
            log.error("更新库存信息失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/history/{productCode}")
    public Result<List<InventoryHistory>> history(
            @PathVariable String productCode,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            log.info("查询库存历史记录，商品编码：{}，开始日期：{}，结束日期：{}", 
                    productCode, startDate, endDate);
            List<InventoryHistory> history = inventoryService.getHistory(productCode, startDate, endDate);
            return Result.success(history);
        } catch (Exception e) {
            log.error("查询库存历史记录失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/stats")
    public Result<Map<String, Integer>> stats() {
        try {
            log.info("获取库存统计信息");
            Map<String, Integer> stats = inventoryService.getStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取库存统计信息失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody Inventory inventory) {
        try {
            log.info("新增库存，商品信息：{}", inventory);
            boolean success = inventoryService.addInventory(inventory);
            return success ? Result.success("新增库存成功", true) : Result.error("新增库存失败");
        } catch (Exception e) {
            log.error("新增库存失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/by-supplier/{supplierId}")
    public Result<List<Map<String, Object>>> getInventoryBySupplier(@PathVariable Long supplierId) {
        try {
            if (supplierId == null) {
                return Result.error("供应商ID不能为空");
            }
            
            // 先获取供应商的所有商品
            List<SupplierProduct> products = supplierProductService.getProductsBySupplierId(supplierId);
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (SupplierProduct product : products) {
                // 查询每个商品的库存信息
                QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
                wrapper.eq("supplier_id", supplierId)
                       .eq("product_id", product.getId());
                Inventory inventory = inventoryService.getOne(wrapper);
                
                Map<String, Object> item = new HashMap<>();
                item.put("product", product);
                item.put("inventory", inventory != null ? inventory : new Inventory());
                result.add(item);
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询供应商库存失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/batch-update")
    public Result<Map<String, Integer>> batchUpdate(@RequestBody List<Map<String, Object>> updates) {
        try {
            if (updates == null || updates.isEmpty()) {
                return Result.error("更新数据不能为空");
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (Map<String, Object> update : updates) {
                try {
                    Long productId = Long.parseLong(update.get("productId").toString());
                    Integer adjustQuantity = Integer.parseInt(update.get("adjustQuantity").toString());
                    
                    if (inventoryService.updateQuantityByProductId(productId, adjustQuantity)) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("批量更新库存失败，数据：{}，原因：{}", update, e.getMessage());
                    failCount++;
                }
            }
            
            Map<String, Integer> result = new HashMap<>();
            result.put("total", updates.size());
            result.put("success", successCount);
            result.put("fail", failCount);
            
            if (failCount == 0) {
                return Result.success("所有库存更新成功", result);
            } else if (successCount > 0) {
                return Result.success(String.format("部分库存更新成功，成功%d个，失败%d个", 
                    successCount, failCount), result);
            } else {
                return Result.error("所有库存更新失败");
            }
        } catch (Exception e) {
            log.error("批量更新库存失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/check-stock")
    public Result<Boolean> checkStock(@RequestBody Map<String, Object> params) {
        try {
            Long productId = Long.parseLong(params.get("productId").toString());
            Integer quantity = Integer.parseInt(params.get("quantity").toString());
            
            boolean sufficient = inventoryService.checkStock(productId, quantity);
            return Result.success(sufficient);
        } catch (Exception e) {
            log.error("检查库存失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    // 删除库存
    @DeleteMapping("/{id}")
    public Result<?> deleteInventory(@PathVariable Long id) {
        try {
            boolean success = inventoryService.deleteInventory(id);
            if (success) {
                return Result.success("删除库存成功");
            } else {
                return Result.error("删除库存失败");
            }
        } catch (Exception e) {
            return Result.error("删除库存失败：" + e.getMessage());
        }
    }
} 